package com.zysdev.videochart

import android.content.Context
import android.hardware.Camera
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import java.io.IOException

class LocalSurfaceView : SurfaceView, Camera.PreviewCallback {

    private var encodecPushLiveH265: EncodecPushLiveH265? = null
    private var camera: Camera? = null
    var cameraSize: Camera.Size? = null
    private var buffer: ByteArray? = null

    constructor(context: Context) : this(context, null)

    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                startPreview()
            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
            }

        })
    }


    public fun startLive(callBck: SocketLive.SocketCallback) {
        encodecPushLiveH265 = EncodecPushLiveH265(callBck, cameraSize!!.width, cameraSize!!.height)
        encodecPushLiveH265!!.startLive()
    }

    private fun startPreview() {
        camera =
            Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK)
//        流程
        //        流程
        val parameters: Camera.Parameters = camera!!.getParameters()
//尺寸
        //尺寸
        cameraSize = parameters.previewSize

        try {
            camera!!.setPreviewDisplay(holder)
            //            横着
            camera!!.setDisplayOrientation(90)
            buffer = ByteArray(cameraSize!!.width * cameraSize!!.height * 3 / 2)
            camera!!.addCallbackBuffer(buffer)
            camera!!.setPreviewCallbackWithBuffer(this)
            //            输出数据怎么办
            camera!!.startPreview()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun onPreviewFrame(data: ByteArray?, camera: android.hardware.Camera?) {
        encodecPushLiveH265?.encodeFrame(data)

        camera?.addCallbackBuffer(data)
    }


}